package org.ns.tomdog.server.nioprotocol;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NioInputStream extends InputStream {

    private SocketChannel socketChannel;

    public SocketChannel getSocketChannel() {
        return socketChannel;
    }

    @Override
    public int read() throws IOException {
        byte[] b = new byte[1];
        int res = read(b);
        if (res == -1) {
            return -1;
        }
        return b[0];
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(len);
        int res = socketChannel.read(byteBuffer);
        if (res <= 0) {
            return res;
        }
        byteBuffer.flip();
        byteBuffer.get(b, off, res);
        return res;
    }

    @Override
    public int read(byte[] b) throws IOException {

        return read(b, 0, b.length);
    }
}
